using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Deepcode.Flux.Core.Services.FileSystem;
using Deepcode.Flux.Core.Systems.Asset;
using Deepcode.Flux.Core.Extensions;

public partial class Private_Asset_Actions : Deepcode.Flux.Core.UI.AdministrationModulePage
{
	#region Permission Code Override
	public override string RequiredPermissionCode { get { return "FluxAmAccess"; } }
	#endregion
	#region Rootpath
	/// <summary>
	/// Specify the root path to use
	/// </summary>
	protected string RootPath
	{
		get
		{
			object o = Session["AssetRootPath"];
			if (o == null) return "~/assets";
			return (string)o;
		}
	}
	#endregion
	#region ViewState and Properties
	/// <summary>
	/// Store the path passed in if appropriate
	/// </summary>
	protected string Path
	{
		get
		{
			object o = ViewState["Path"];
			if( o == null ) return "";
			return (string) o;
		}
		set
		{
			ViewState["Path"] = value;
		}
	}
	/// <summary>
	/// Store the filename selected if appropriate
	/// </summary>
	protected string SelectedFilename
	{
		get
		{
			object o = ViewState["SelFile"];
			if( o == null ) return "";
			return (string) o;
		}
		set
		{
			ViewState["SelFile"] = value;
		}
	}
	/// <summary>
	/// Get the current file mask
	/// </summary>
	protected string CurrentFileMask
	{
		get
		{
			return UserSetting("ASSETFILEMASK", "*.*");
		}
	}
	#endregion
	#region Page Load Event
	/// <summary>
	/// Page Load event
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void Page_Load(object sender, EventArgs e)
	{
		if (!Page.IsPostBack)
		{
			// Load path data
			Path = GetAttribute("Path", "");
			SelectedFilename = "";
			
			// If no path passed in, user last known path from registry
			if (Path == "")
				Path = UserSetting("ASSETMANAGERLASTPATH", this.RootPath);

			// Ensure path exists - default to assets if not
			string fullpath = Server.MapPath(Path);
			if (!System.IO.Directory.Exists(fullpath))
			{
				// If it's a file - select the file (provided it exists of course)
				if (System.IO.File.Exists(fullpath))
				{
					SelectedFilename = Path.Substring(Path.LastIndexOf('/')+1);
					Path = Path.Substring(0, Path.LastIndexOf('/'));
					fullpath = Server.MapPath( Path );
					if( !System.IO.Directory.Exists( fullpath )) Path=this.RootPath;
				}
				else
					Path = this.RootPath;
			}
			// Ensure path is in rootpath
			if( ! Path.StartsWith(this.RootPath) ) Path = this.RootPath;

			// Display the path in the panel
			breadcrumbs.Text = BuildBreadcrumbs(Path.Substring(1), SelectedFilename);

			// Get the actions
			BindAvailableActions();

			// Output refresh scripts if necessary
			if( GetAttribute("refreshFolders", "") != "" )
				ClientScript.RegisterStartupScript(typeof(Private_Asset_Actions),
					"folderrefresh", 
					String.Format("this.parent.loadFolders('{0}');", this.Path)
					, true);

			if( GetAttribute("refreshFiles", "") != "" )
				ClientScript.RegisterStartupScript(typeof(Private_Asset_Actions),
					"filerefresh", 
					String.Format("this.parent.loadfiles('{0}');", this.Path)
					, true);
		}
	}
	#endregion
	#region Page_Init Event
	/// <summary>
	/// Page is initialising
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void Page_Init(object sender, System.EventArgs e)
	{
		actionList.ItemDataBound += new DataListItemEventHandler(actionList_ItemDataBound);
		actionList.ItemCommand += new DataListCommandEventHandler(actionList_ItemCommand);
	}
	#endregion
	#region Utility
	/// <summary>
	/// Builds a list of anchors for the current path/filename
	/// </summary>
	/// <param name="path"></param>
	/// <param name="fname"></param>
	/// <returns></returns>
	protected string BuildBreadcrumbs(string path, string fname)
	{
		string res = "/";
		string fullpath = "~/";
		string [] dirs = path.Split('/');

		foreach( string dir in dirs )
		{
			if (dir != "")
			{
				fullpath += dir;
				if( fullpath.StartsWith( this.RootPath ))
					res += "<a class='breadcrumb' href=\"javascript:this.parent.loadEverything('" + fullpath + "');\">" + dir + "</a>";
				else
					res += dir;
				res += "/";
				fullpath += "/";
			}
		}

		if( fname != "" ) res += fname;
		return res;
	}
	#endregion
	#region Data Binding
	/// <summary>
	/// Put the list of actions on the data list
	/// </summary>
	protected void BindAvailableActions()
	{
		Deepcode.Flux.Core.Codons.Asset.AssetActionContext context = 
			new Deepcode.Flux.Core.Codons.Asset.AssetActionContext(this.Page, this.Path, this.SelectedFilename);

		AddinTreeNode root = AddinTree.Tree.GetTreeNodeNoThrow("/Flux/Asset/Actions/");
		if( root == null ) return;

		actionList.DataSource = root.BuildChildItems(context);
		actionList.DataBind();

	}
	/// <summary>
	/// Item has been bound to the data list
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	void actionList_ItemDataBound(object sender, DataListItemEventArgs e)
	{
		if( !(e.Item.ItemType == ListItemType.AlternatingItem ||
			e.Item.ItemType == ListItemType.EditItem ||
			e.Item.ItemType == ListItemType.Item ||
			e.Item.ItemType == ListItemType.SelectedItem) ) return;

		Button button = (Button) e.Item.FindControl("actionButton");
		if( button == null ) return;

		if( e.Item.DataItem == null ) return;
		if( !(e.Item.DataItem is AssetActionButton) ) return;
		AssetActionButton b = (AssetActionButton) e.Item.DataItem;

		button.Text = b.Caption;
		if (b.PreActionScript != "")
			button.OnClientClick = b.PreActionScript;

		if (b.Target != "")
		{
			button.OnClientClick =
				String.Format("PreviewWindow('{0}', '{1}');", b.ActionUrl, b.Target );
		}
		else
		{
			button.CommandArgument = b.ActionUrl;
		}
	}
	/// <summary>
	/// Command button was clicked
	/// </summary>
	/// <param name="source"></param>
	/// <param name="e"></param>
	void actionList_ItemCommand(object source, DataListCommandEventArgs e)
	{
		if( e.CommandArgument == null || (((string) e.CommandArgument) == "") ) return;
	
		Response.Redirect(((string) e.CommandArgument), true);
	}
	#endregion
}
